package com.tdk.wifidirectserver.ui.nsd

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.tdk.wifidirectserver.adapter.NsdServiceInfoDiff
import com.tdk.wifidirectserver.adapter.ServerInfoAdapter
import com.tdk.wifidirectserver.databinding.FragmentNsdServerItemListBinding
import com.tdk.wifidirectserver.ui.main.ConnectedClientViewModel

/**
 * A fragment representing a list of Items.
 */
class NsdClientItemFragment : Fragment() {
    private lateinit var serverInfoAdapter: ServerInfoAdapter
    lateinit var binding: FragmentNsdServerItemListBinding
    private var connectedClientViewModel: ConnectedClientViewModel? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentNsdServerItemListBinding.inflate(inflater, container, false)
        initView()
        return binding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initView() {
        serverInfoAdapter = ServerInfoAdapter(NsdServiceInfoDiff())
        binding.messageRv.adapter = serverInfoAdapter
        binding.messageRv.layoutManager =
            LinearLayoutManager(this.requireContext(), LinearLayoutManager.VERTICAL, false)

        connectedClientViewModel?.serviceInfoList?.observe(viewLifecycleOwner) {
                Log.d(TAG, "serviceInfoList:${it.size} ")
                serverInfoAdapter.submitList(it)
                serverInfoAdapter.notifyDataSetChanged()

        }

        serverInfoAdapter.onItemClickListener = {
            val ip = if (Build.VERSION.SDK_INT >= 34) {
                it.hostAddresses[0].hostAddress
            } else {
                it.host.hostAddress
            }
            connectedClientViewModel?.startClient(ip,it.port)
        }

    }

    companion object {

        const val TAG = "NsdClientItemFragment"

        @JvmStatic
        fun newInstance(viewModel: ConnectedClientViewModel) =
            NsdClientItemFragment().apply {
                Log.d(TAG, "newInstance: NsdClientItemFragment")
                this.connectedClientViewModel = viewModel
            }
    }
}